﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BrnMall.Manager.Domain.WeApp;
using BrnMall.Manager.Manager.WeApp;
using BrnMall.Sdk.WeiXin;
using BrnMall.Sdk.WeiXin.weapp;
using BrnMall.WeiXin.Sdk;
using Newtonsoft.Json;
using PetaPoco;
using WeiTap.Restful;

namespace QIDong.WeApp.Controllers
{
    /// <summary>
    ///小程序模板管理
    /// </summary>
    public class WeApplicationController : WebApi
    {
        /// <summary>
        /// 添加系统小程序模板
        /// </summary>
        /// <param name="app"></param>
        public void AddApp(WeApplication app)
        {
            WeApplicationManager.AddApplication(app);
        }
        /// <summary>
        /// 更新模板的TabBar配置信息
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="tabJson"></param>
        public void UpdateAppTabBar(int appid, string tabJson)
        {

            if (string.IsNullOrEmpty(tabJson)) throw new ArgumentNullException(nameof(tabJson));
            var tabPages = JsonConvert.DeserializeObject<TabBarPages>(tabJson);
            if (tabPages == null)
                throw new ArgumentException(nameof(tabJson));
            var app = WeApplicationManager.GetWeApplication(appid);
            if (app == null) throw new ArgumentException(nameof(appid));
            app.RawTabBar = tabJson;
            WeApplicationManager.UpdateApplication(app);
        }
        /// <summary>
        /// 添加模板的页面配置信息
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="pages"></param>
        public void AddAppPages(int appid, string pages)
        {
            var weapp = WeApplicationManager.GetWeApplication(appid);
            
            var oldpages = JsonConvert.DeserializeObject<IList<string>>(weapp.RawPages) ?? new List<string>();
            var newPages = JsonConvert.DeserializeObject<IList<string>>(pages);
            if (newPages != null)
            {
                foreach (var page in newPages)
                {
                    oldpages.Add(page);
                }
            }
            weapp.RawPages = JsonConvert.SerializeObject(oldpages);
            WeApplicationManager.UpdateApplication(weapp);
        }
        /// <summary>
        /// 单个添加模板的页面配置信息
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="pageUrl"></param>
        public void AddAppSinglePage(int appid, string pageUrl)
        {
            var weapp = WeApplicationManager.GetWeApplication(appid);

            var oldpages = JsonConvert.DeserializeObject<IList<string>>(weapp.RawPages) ?? new List<string>();
            if(!oldpages.Contains(pageUrl,StringComparer.InvariantCultureIgnoreCase))
                    oldpages.Add(pageUrl);
             
            weapp.RawPages = JsonConvert.SerializeObject(oldpages);
            WeApplicationManager.UpdateApplication(weapp);
        }
        /// <summary>
        /// 移除模板的页面配置信息
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="pageUrl"></param>
        public void RemoveAppPages(int appid, string pageUrl)
        {
            if (string.IsNullOrEmpty(pageUrl))
            {
                throw new ArgumentNullException(nameof(pageUrl));
            }
            var weapp = WeApplicationManager.GetWeApplication(appid);
            var oldpages = JsonConvert.DeserializeObject<IList<string>>(weapp.RawPages) ?? new List<string>();
            oldpages.Remove(pageUrl);
            weapp.RawPages = JsonConvert.SerializeObject(oldpages);
            WeApplicationManager.UpdateApplication(weapp);
        }
        /// <summary>
        /// 移除模板的页面配置信息
        /// </summary>
        /// <param name="appid"></param>
        public void ClearAppPages(int appid)
        {
            
            var weapp = WeApplicationManager.GetWeApplication(appid);
            weapp.RawPages =string.Empty;
            WeApplicationManager.UpdateApplication(weapp);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="app"></param>
        public void UpdateApp(WeApplication app)
        {
            WeApplicationManager.UpdateApplication(app);
        }

        /// <summary>
        /// 更新模板编号
        /// </summary>
        /// <param name="appId">小程序模板ID</param>
        /// <param name="templateId">模板编号</param>
        public BaseResult UpdateTemplateId(int appId, int templateId)
        {
            var weapp = WeApplicationManager.GetWeApplication(appId);
            WeApplicationManager.UpdateApplicationTemplate(appId, templateId);
            var users = WeApplicationManager.GetWeApplicationsByTemplateId(weapp.TemplateId);
            if (users.Count > 0) return new BaseResult { errcode = -2, errmsg = "更新模板成功，不能删除正在使用的模板，属于正常现象" };
            var platform = WeApplicationManager.GetDefaultApplicationPlatform();
            return WeAppSdk.DeleteTemplate(platform.Component_Access_Token, weapp.TemplateId);



        }
        /// <summary>
        /// 获取模板信息
        /// </summary>
        /// <param name="appid">小程序模板ID</param>
        /// <returns></returns>
        public WeApplication Get(int appid)
        {
            return WeApplicationManager.GetWeApplication(appid);
        }

        /// <summary>
        /// 获取系统小程序模板
        /// </summary>
        /// <param name="pageNumber">当前页码</param>
        /// <param name="itemsPerPage">每页多少条</param>
        /// <returns></returns>
        public Page<WeApplication> GetWeApps(int pageNumber = 1, int itemsPerPage = 15)
        {
            return WeApplicationManager.GetApplicatioinPage(pageNumber, itemsPerPage);
        }
        /// <summary>
        /// 解决有些客户上传模板失效的问题
        /// </summary>
        public void UpdateAllStoreAppTemplateId()
        {
            var apps = WeApplicationManager.GetApplicatioinPage(1, 999);
            var items = apps.Items;
            foreach (var item in items)
            {
                WeApplicationManager.UpdateApplicationTemplate(item.AppId, item.TemplateId);
            }
        }
    }
}
